package cn.tedu.mall.seckill.controller;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.JsonResult;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.pojo.seckill.vo.SeckillCommitVO;
import cn.tedu.mall.seckill.exception.SeckillBlockHandler;
import cn.tedu.mall.seckill.exception.SeckillFallback;
import cn.tedu.mall.seckill.service.ISeckillService;
import cn.tedu.mall.seckill.utils.SeckillCacheUtils;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.text.rtf.RTFEditorKit;

@RestController
@RequestMapping("/seckill")
@Api(tags = "随机码验证并提交订单")
public class SeckillController {
    @Autowired
    private ISeckillService seckillService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/{randCode}")
    @ApiOperation("随机码验证并提交订单")
    @ApiImplicitParam(value = "随机码",name = "randCode",required = true)
    @PreAuthorize("hasRole('user')")
    @SentinelResource(value = "seckill",
            blockHandlerClass = SeckillBlockHandler.class,blockHandler = "seckillBlock",
            fallbackClass = SeckillFallback.class,fallback = "seckillFallback")
    public JsonResult<SeckillCommitVO> commitSeckill(@PathVariable String randCode,@Validated SeckillOrderAddDTO seckillOrderAddDTO){
        System.out.println("随机码为:"+randCode);
        Long spuId = seckillOrderAddDTO.getSpuId();
        String randCodeKey = SeckillCacheUtils.getRandCodeKey(spuId);
        //判断redis是否有key
        if(redisTemplate.hasKey(randCodeKey)){
            String redisRandCode = redisTemplate.boundValueOps(randCodeKey).get()+"";
            //判断redis中的随机码和参数中的随机码不同
            if(!redisRandCode.equals(randCode)){
                throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"没有找到指定商品!");
            }
            SeckillCommitVO seckillCommitVO = seckillService.commitSeckill(seckillOrderAddDTO);
            System.out.println("购买成功!");
            return JsonResult.ok(seckillCommitVO);
        }else {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"没有找到指定商品!");
        }



    }










}
